package main

import (
	"encoding/json"
	"flag"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/nggs/tools/print"
	"gitee.com/nggs/tools/static_data"
	"gitee.com/nggs/util"
)

var (
	flagConfigFilePath = flag.String("cfg", "./gen_static_data_json.json", "cfg file path, default = ./gen_static_data_json.json")
)

func main() {
	flag.Parse()

	cfg, err := loadConfig(*flagConfigFilePath)
	if err != nil {
		panic(err)
	}

	jsonDir, err := filepath.Abs(cfg.JsonDir)
	if err != nil {
		panic(err)
	}

	util.MustMkdirIfNotExist(jsonDir)

	if cfg.Debug {
		print.SetDebugMode(true)
	}

	staticData := static_data.New()

	if cfg.EnumFilePath != "" {
		staticData.Enums, err = static_data.ReadEnum(cfg.EnumFilePath)
		if err != nil {
			panic(err)
			return
		}
	}

	if cfg.TypeFilePath != "" {

	}

	err = util.Walk(cfg.ExcelDir, "xlsx", cfg.WhiteList, cfg.BlackList, func(path string, info os.FileInfo, name string, isInBlackList bool) bool {
		if isInBlackList {
			print.Infof("[%s]在黑名单中，跳过", path)
			return true
		}

		if strings.HasPrefix(info.Name(), "~$") {
			print.Debugf("跳过临时文件[%s]", path)
			return true
		}

		if path == cfg.EnumFilePath {
			print.Debugf("跳过枚举文件[%s]", path)
			return true
		}

		if path == cfg.TypeFilePath {
			print.Debugf("跳过类型文件[%s]", path)
			return true
		}

		print.Infof("<- %s", path)

		e, err := static_data.Read(path, cfg.TableTags, cfg.AttributeTags, cfg.DataTags, true, staticData, cfg.ClientMode)
		if err != nil {
			print.Errorf("读取[%s]失败，%s", path, err)
			return true
		}

		for _, s := range e.Sheets {
			jsonPath := filepath.Join(jsonDir, s.Name+".json")
			var content []byte
			if cfg.Indent != "" {
				content, err = json.MarshalIndent(s, "", cfg.Indent)
			} else {
				content, err = json.Marshal(s)
			}
			if err != nil {
				print.Errorf("序列化[%s]失败，%s", s.Name, err)
				return true
			}
			err = ioutil.WriteFile(jsonPath, content, 0766)
			if err != nil {
				print.Errorf("写入[%s]失败，%s", jsonPath, err)
				return true
			}

			print.Infof("-> %s", jsonPath)
		}
		return true
	})
	if err != nil {
		panic(err)
	}
}
